<script setup>
import { computed, inject, onMounted, ref } from 'vue'
import { DlMessageBox } from '../util/messagebox.js';
//图标
import { IconArrowLeft, IconDecreaseCircle, IconPlusCircle, IconStarLine, IconStarFill, IconChatAlt, IconCart } from '../icon/index.js'
import BannerBox from '../components/BannerBox.vue'
import DlLoading from '../components/DlLoading.vue'
import StarBox from '../components/StarBox.vue'

//引入 api
import { findProductByIdFun } from '../api/product.js'
import { addToCartFun } from '../api/cart.js'
import { buyNowFun } from '../api/order.js'
import { findCommentsFun } from '../api/comment.js'

//主菜单核心
const menuCore = inject('menuCore');

//返回
function doGoBack() {
    menuCore.back();
}

//当前商品
const product = ref({});
const typeArr = ref([]);//商品的可选规格
const bannerArr = ref([]);
function doLoadData() {
    //加载商品信息
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            //测试数据
            let p = {
                id: productId,
                title: '休闲男士衬衫百搭',
                type: ['L','XL','XXL'],//商品的可选规格
                price: 39.89,//售价
                sellCount: 3981,//销量
                store: 7456,//库存
                image: './product/product1.jpg',//封面
                details: [ // 详情图片
                    './product/product1.jpg',
                    './banner1.jpg',
                    './banner2.jpg',
                ]
            };
    
            //是否已收藏
            p.collected = false;
            //成功后执行以下操作
            typeArr.value = p.type;
            bannerArr.value = p.details;
            //封面加入banner
            //bannerArr.value.unshift(p.image);
            product.value = p;
        }, 1000);
    } else {
        //请求api
        findProductByIdFun(productId).then((result)=>{
            console.log('findProductByIdFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);

                let p = result.data;
                typeArr.value = p.type;
                bannerArr.value = p.details;
                // 封面加入banner
                //bannerArr.value.unshift(p.image);
                product.value = p;
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//选择规格、数量
const selectType = ref('');
const selectCount = ref(1);
function doTypeSelect(type) {
    if(selectType.value == type) {
        type = '';
    }
    selectType.value = type;
}
//数量增减
function doCountPlus(val) {
    let c = selectCount.value;
    c += val;
    if(c < 1) {
        c = 1;
    }
    selectCount.value = c;
}

// 详情/评价 切换
const selectTab = ref('detail');
function doChangeTab(tab) {
    selectTab.value = tab;
    if (tab == 'comment' && pages.value == 0) {//没有数据,则重新查询
        currentPageNum.value = 1;
        commentArr.value = [];
        doLoadDataComment();
    }
}


//底部菜单操作
//收藏
function doCollect() {
    DlMessageBox.warning('研发中...');
}
//客服
function doUserServer() {
    DlMessageBox.warning('研发中...');
}
//去购物车
function goToCart() {
    menuCore.push('/cart');
}
//购物车
const cart = inject('cart');
//加入购物车
function doAddCart() {
    if(!isLogin.value) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        return;
    }
    if(!selectType.value) {
        DlMessageBox.warning('请选择规格参数!');
        return;
    }
    //加入购物车
    let p = product.value;
    console.log('doAddCart:', p);

    let params = {
        productId: p.id,
        num: selectCount.value,
        type: selectType.value
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        if(cart[p.id]){
            cart[p.id].num += selectCount.value;
            //覆盖 规格
            cart[p.id].selectType = selectType.value;
        } else {
            cart[p.id] = {productId: p.id, image: p.image, title: p.title, price: p.price, type: p.type, selectType: selectType.value, num: selectCount.value, checked: false};
        }
        //成功后执行以下操作
        DlMessageBox.success('加入成功');
        //console.log('cart:', cart);
    } else {
        //请求api
        addToCartFun(params.productId, undefined, params.num, params.type).then((result)=>{
            console.log('addToCartFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}
//立即购买
function doAddOrder() {
    let params = {
        productId: product.value.id, 
        num: selectCount.value, 
        selectType: selectType.value
    };
    console.log('params:', params);
    if(!isLogin.value) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        return;
    }
    if(!params.selectType) {
        DlMessageBox.warning('请选择规格参数!');
        return;
    }
    //购买操作
    if (window && window.enableDl) {
        //模拟
        //成功后执行以下操作
        DlMessageBox.success('下单成功');
        //成功后去支付
        localStorage.setItem('orderId', 2);
        menuCore.push('/pay');
    } else {
        //请求api
        buyNowFun(params.productId, params.num, params.selectType).then((result)=>{
            console.log('buyNowFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后去支付
                localStorage.setItem('orderId', result.data);//订单id
                menuCore.push('/pay');
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//评价数据
const commentArr = ref([]);
const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);
const noMoreData = ref(false);//是否已无更多数据了
const commentLoading = ref(false);
function doLoadDataComment() {
    noMoreData.value = false;
    commentLoading.value = true;
    //加载评论
    let params = {
        productId: productId,
        pageNum: currentPageNum.value,
        pageSize: pageSize
    };
    console.log('doLoadDataComment-params:', params);
    
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            let key = commentArr.value.length;
            for(let i1; i<6; i++) {
                dataArr.push({ id: (i+key), content: '很不错，很不错-'+(i+key), star: 4, 
                    user: {nickname:'乔治',headImage:'./user_default.jpg'},
                    productType: '红色',
                    createTime: '2024-07-20 18:23:42'
                });
            }
            //成功后执行以下操作
            dataArr.forEach(c => commentArr.value.push(c));
            pages.value = 5;
            commentLoading.value = false;
            noMoreData.value = currentPageNum.value >= pages.value;
        }, 1000);
    } else {
        //请求api
        findCommentsFun(params.productId, params.pageNum, params.pageSize).then((result)=>{
            console.log('findCommentsFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                let data = result.data;
                data.list.forEach(c => commentArr.value.push(c));
                pages.value = data.pages;
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            commentLoading.value = false;
        });
    }
}

//滚动事件
function doChangeScroll(e) {
    //不展示评价时不加载评价
    if(selectTab.value != 'comment') {
        return;
    }
    let t = e.target;
    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!commentLoading.value && !noMoreData.value) {
            currentPageNum.value++;
            doLoadDataComment();
        }
    }
}

//登录用户缓存
const loginUser = inject('loginUser');
//是否登录
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        //DlMessageBox.error('您还未登录,\n请先登录!');
        return;
    }
    isLogin.value = true;
}

let productId = null;// 商品id
onMounted(()=>{
    //获取从其他地方跳转到此页面时, 需要的参数 productId
    let id = parseInt(localStorage.getItem('detailProductId'));
    if(!isNaN(id)) {
        productId = id;
    }

    doLoadData();
    doCheckLogin();
});

</script>
<template>
    <div class="view-dl" @scroll="doChangeScroll" >
        <!-- 顶部 -->
        <div class="top-head-dl">
            <IconArrowLeft class="back-icon" @click="doGoBack" />
            <div class="title-dl">商品详情</div>
        </div>

        <!-- 横幅展示 -->
        <BannerBox class="banner-div-dl" :arr="bannerArr" :autoplay="false" ></BannerBox>

        <!-- 主体 -->
        <div class="view-body-dl">
            <!-- 基本信息 -->
            <div class="product-info-dl">
                <div class="price-box-dl">
                    <div class="price-dl">￥{{product.price}}</div>
                    <!-- <div class="price-old-dl">￥{{product.price}}</div> -->
                </div>
                <div class="title-box-dl">
                    <div class="title-item-dl">{{product.title}}</div>
                </div>
                <div class="tip-list-dl">
                    <div class="tip-item-dl">
                        <span class="tip-label-dl">销量：</span>
                        <span class="tip-value-dl">{{product.sellCount}}</span>
                    </div>
                    <div class="tip-item-dl">
                        <span class="tip-label-dl">库存：</span>
                        <span class="tip-value-dl">{{product.store}}</span>
                    </div>
                </div>
            </div>
            <!-- 规格选择 -->
            <div class="type-box-dl">
                <div class="type-label-dl">规格参数：</div>
                <div class="type-list-dl">
                    <div class="type-item-dl" :class="(t==selectType?'type-item-active-dl':'')" v-for="t in typeArr" :key="t"
                    @click="doTypeSelect(t)">{{t}}</div>
                </div>
                <div class="type-label-dl">数量：</div>
                <div class="num-box-dl">
                    <IconDecreaseCircle class="icon-dl" @click="doCountPlus(-1)"/>
                    <div class="num-value-dl" >{{selectCount}}</div>
                    <IconPlusCircle class="icon-dl" @click="doCountPlus(1)"/>
                </div>
            </div>
            
            <!-- 详情, 评论 -->
            <div class="tab-list-dl">
                <div class="tab-menu-list-dl">
                    <div class="tab-menu-item-dl" style="border-top-left-radius: 0.1rem;" :class="(selectTab == 'detail'?'tab-active-dl':'')" @click="doChangeTab('detail')" >详情</div>
                    <div class="tab-menu-item-dl" style="border-top-right-radius: 0.1rem;" :class="(selectTab == 'comment'?'tab-active-dl':'')" @click="doChangeTab('comment')" >评价</div>
                </div>
                <!-- 详情 -->
                <div class="tab-body-dl detail-list-dl" v-show="selectTab == 'detail'">
                    
                    <template v-for="d in product.details" :key="d">
                        <img class="detail-img" :src="d" alt="no image">
                    </template>

                </div>
                <!-- 评论 -->
                <div class="tab-body-dl comment-list-dl" v-show="selectTab == 'comment'">
                    
                    <div class="comment-item-dl" v-for="c in commentArr" :key="c.id">
                        <div class="comment-top-dl">
                            <div class="user-img-dl">
                                <img :src="c.user.headImage" alt="no image">
                            </div>
                            <div class="user-nickname-dl">{{c.user.nickname}}</div>
                            <StarBox class="star-score-dl" :count="3" />
                        </div>
                        <div class="comment-type-time-dl">
                            <div class="type-dl">规格：{{c.productType}}</div>
                            <div class="time-dl">{{c.createTime}}</div>
                        </div>
                        <div class="comment-content-dl">{{c.content}}</div>
                    </div>

                    <div class="load-box-dl" >
                        <DlLoading style="font-size: 1rem" v-show="commentLoading" />
                        <div class="no-more-data-dl" v-show="!commentLoading && noMoreData">暂无更多评论</div>
                    </div>
                </div>

                
            </div>
        </div>

        <!-- 回到顶部 -->

        <!-- 底部菜单 -->
        <div class="foot-menu-box-dl">
            <div class="foot-menu-icon-dl" @click="doCollect">
                <IconStarFill class="icon-dl" v-show="product.collected"/>
                <IconStarLine class="icon-dl" v-show="!product.collected" />
                <div class="tip-title-dl">收藏</div>
            </div>
            <div class="foot-menu-icon-dl" @click="doUserServer">
                <IconChatAlt class="icon-dl" />
                <div class="tip-title-dl">客服</div>
            </div>
            <div class="foot-menu-icon-dl" @click="goToCart">
                <IconCart class="icon-dl" />
                <div class="tip-title-dl">购物车</div>
            </div>
            <div class="foot-menu-dl add-cart" @click="doAddCart">加入购物车</div>
            <div class="foot-menu-dl add-order" @click="doAddOrder">立即购买</div>
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    height: 100%;
    overflow: hidden auto;
}
.top-head-dl {
    background-color: #fff;
    color: #333;
    padding: 0.2rem;
    position: relative;
}
.top-head-dl .back-icon {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.top-head-dl .title-dl {
    font-size: 0.7rem;
    text-align: center;
}

.banner-div-dl {
    height: 6rem;
    font-size: 0.8rem;
    background-color: #eee;
}

.view-body-dl {
    padding: 0.2rem 0.2rem 1.6rem;
}

.product-info-dl {
    margin-bottom: 0.2rem;
    padding: 0.2rem;
    background-color: #fff;
    border-radius: 0.1rem;
}
.price-box-dl {
    font-weight: bold;
    margin-bottom: 0.2rem;
}
.price-dl {
    color: #a00;
    font-size: 0.5rem;
    display: inline-block;
    margin-right: 0.2rem;
}
.price-old-dl {
    color: #999;
    text-decoration: line-through;
    font-size: 0.32rem;
    display: inline-block;
}
.title-box-dl {
    font-size: 0.4rem;
    margin-bottom: 0.2rem;
}
.title-item-dl {
    font-weight: bold;
}
.tip-list-dl {
    color: #999;
    font-size: 0.36rem;
    display: flex;
    justify-content: space-between;
}
.tip-item-dl {
    flex-shrink: 0;
}

.type-box-dl {
    padding: 0.2rem;
    background-color: #fff;
    border-radius: 0.1rem;
    font-weight: bold;
    font-size: 0.4rem;
    margin-bottom: 0.2rem;
}
.type-label-dl {
    color: #999;
    margin-bottom: 0.1rem;
}
.type-list-dl {
    display: flex;
    flex-wrap: wrap;
}
.type-item-dl {
    border: 1px solid #999;
    padding: 0.08rem 0.2rem;
    margin: 0 0.2rem 0.2rem 0;
    cursor: pointer;
    color: #666;
}
.type-item-active-dl {
    color: #900;
    border: 1px solid #900;
}
.num-box-dl {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
.num-box-dl .icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    flex-shrink: 0;
}
.num-value-dl {
    min-width: 1.2rem;
    padding: 0 0.2rem;
    display: inline-block;
    text-align: center;
    font-size: 0.6rem;
    flex-shrink: 0;
}

.tab-list-dl {
    background-color: #fff;
    border-radius: 0.1rem;
}
.tab-menu-list-dl {
    display: flex;
    font-weight: bold;
}
.tab-menu-item-dl {
    flex: 1 0 auto;
    text-align: center;
    border: 1px solid #ccc;
    padding: 0.2rem;
    margin: 1px;
    cursor: pointer;
}
.tab-active-dl {
    color: #3070EB;
}
.tab-body-dl {
    padding: 0.2rem;
}
.detail-list-dl {
    font-size: 0;
}
.detail-img {
    width: 100%;
    height: auto;
}


.comment-list-dl {
    min-height: 5rem;
}
.comment-item-dl {
    margin: 0.2rem 0;
    border-bottom: 1px solid #ccc;
}
.comment-top-dl {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.comment-top-dl .user-img-dl {
    width: 1.2rem;
    height: 1.2rem;
    overflow: hidden;
    border-radius: 50%;
    flex-shrink: 1;
}
.user-img-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}
.comment-top-dl .user-nickname-dl {
    font-size: 0.48rem;
    flex: 1 0 auto;
    margin: 0 0.28rem;
}
.comment-top-dl .star-score-dl {
    font-size: 0.6rem;
    flex-shrink: 0;
}

.comment-type-time-dl {
    color: #999;
    display: flex;
    margin: 0.2rem 0;
    justify-content: space-between;
}
.comment-type-time-dl .type-dl {
    font-size: 0.4rem;
}
.comment-type-time-dl .time-dl {
    font-size: 0.4rem;
}
.comment-content-dl {
    font-size: 0.4rem;
    margin: 0.2rem 0;
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin-top: 0.5rem;
    padding: 0.2rem;
}
.load-box-dl .no-more-data-dl {
    /* border-top: 1px solid #ccc; */
    font-size: 0.4rem;
    padding: 0.2rem 0;
}

.foot-menu-box-dl {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    height: 1.2rem;
    font-size: 0.24rem;
    color: #333;
    display: flex;
    align-items: center;
    padding: 0.1rem;
    box-sizing: border-box;
    z-index: 9;
}
.foot-menu-icon-dl {
    width: 1rem;
    padding: 0 0.1rem;
    flex-shrink: 0;
    text-align: center;
    cursor: pointer;
    border-right: 1px solid #ccc;
    height: 1rem;
}
.foot-menu-icon-dl .icon-dl {
    width: 0.6rem;
    height: 0.6rem;
}
.foot-menu-dl {
    flex: 1 0 auto;
    padding: 0 0.1rem;
    text-align: center;
    cursor: pointer;
    font-size: 0.4rem;
    height: 1rem;
    line-height: 1rem;
}
.add-cart {
    border-right: 1px solid #ccc;
}


</style>